package mcore

import (
	"fmt"
	"io"
	"mime/multipart"
	"os"
	"path"
)

var FileUpload = &upload{}

type upload struct {
}

func (domain *upload) LocalStorage(multipartFile multipart.File, basePath string, storageFilename string) (writePath string, errs error) {
	fileBytes, err := io.ReadAll(multipartFile)
	if err != nil {
		return "", err
	}
	_, err = os.Stat(basePath)
	if os.IsNotExist(err) {
		err = os.MkdirAll(basePath, 0666)
		if err != nil {
			return "", err
		}
	} else if os.IsExist(err) {
		return "", err
	}
	writePath = path.Join(basePath, storageFilename)
	return writePath, os.WriteFile(writePath, fileBytes, 0666)
}

func (domain *upload) LocalStorageNewName(multipartFile multipart.File, basePath string, storageFilename string) error {
	fileBytes, err := io.ReadAll(multipartFile)
	if err != nil {
		return err
	}
	dateStr := DateUtil.NowDateTime().Format(DateUtil.DateFormatNumber)
	filepath := path.Join(basePath, dateStr)
	_, err = os.Stat(filepath)
	if os.IsNotExist(err) {
		err = os.MkdirAll(filepath, 0666)
		if err != nil {
			return err
		}
	}
	for true {
		filename := fmt.Sprintf("%s%s", RandomUtil.UniqueId(fmt.Sprintf("%s-", RandomUtil.NextXAZ(1)), 26), path.Ext(storageFilename))
		err = os.WriteFile(path.Join(filepath, filename), fileBytes, 0666)
		if os.IsExist(err) {
			continue
		}
		return err
	}
	return nil
}
